<template>
  <div class="duty-record-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>值班记录</span>
          <el-button type="primary" @click="handleAdd">新增记录</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="护士">
          <el-select
            v-model="searchForm.nurseId"
            placeholder="选择护士"
            clearable
          >
            <el-option
              v-for="nurse in nurses"
              :key="nurse.id"
              :label="nurse.name"
              :value="nurse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排班">
          <el-select
            v-model="searchForm.scheduleId"
            placeholder="选择排班"
            clearable
          >
            <el-option
              v-for="schedule in schedules"
              :key="schedule.id"
              :label="`${schedule.nurseName} - ${formatDate(
                schedule.dutyDate
              )}`"
              :value="schedule.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 值班记录表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="nurseName" label="护士姓名" width="120" />
        <el-table-column prop="scheduleInfo" label="排班信息" width="200">
          <template #default="{ row }">
            {{ formatDate(row.dutyDate) }} -
            {{ getShiftTypeText(row.shiftType) }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button type="danger" link @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增值班记录' : '编辑值班记录'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="护士" prop="nurseId">
          <el-select v-model="form.nurseId" placeholder="选择护士">
            <el-option
              v-for="nurse in nurses"
              :key="nurse.id"
              :label="nurse.name"
              :value="nurse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排班" prop="scheduleId">
          <el-select v-model="form.scheduleId" placeholder="选择排班">
            <el-option
              v-for="schedule in schedules"
              :key="schedule.id"
              :label="`${schedule.nurseName} - ${formatDate(
                schedule.dutyDate
              )}`"
              :value="schedule.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="异常" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { formatDate, formatDateTime } from "@/utils/date";
import {
  getDutyRecords,
  createDutyRecord,
  updateDutyRecord,
  deleteDutyRecord,
} from "@/api/duty";
import { getNurses } from "@/api/nurse";
import { getDutySchedules } from "@/api/duty";

// 数据
const loading = ref(false);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const nurses = ref([]);
const schedules = ref([]);

// 搜索表单
const searchForm = reactive({
  nurseId: null,
  scheduleId: null,
});

// 表单数据
const dialogVisible = ref(false);
const dialogType = ref("add");
const formRef = ref(null);
const form = reactive({
  id: null,
  nurseId: null,
  scheduleId: null,
  startTime: null,
  endTime: null,
  status: 1,
});

// 表单验证规则
const rules = {
  nurseId: [{ required: true, message: "请选择护士", trigger: "change" }],
  scheduleId: [{ required: true, message: "请选择排班", trigger: "change" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 获取班次类型文本
const getShiftTypeText = (type) => {
  const types = {
    1: "早班",
    2: "中班",
    3: "晚班",
  };
  return types[type] || "未知";
};

// 获取状态文本和类型
const getStatusText = (status) => {
  const statusMap = {
    0: "异常",
    1: "正常",
  };
  return statusMap[status] || "未知";
};

const getStatusType = (status) => {
  const typeMap = {
    0: "danger",
    1: "success",
  };
  return typeMap[status] || "info";
};

// 获取值班记录列表
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    };
    const res = await getDutyRecords(params);
    tableData.value = res.records;
    total.value = res.total;
  } catch (error) {
    console.error("获取值班记录列表失败:", error);
    ElMessage.error("获取值班记录列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取护士列表
const fetchNurses = async () => {
  try {
    const res = await getNurses();
    nurses.value = res;
  } catch (error) {
    console.error("获取护士列表失败:", error);
    ElMessage.error("获取护士列表失败");
  }
};

// 获取排班列表
const fetchSchedules = async () => {
  try {
    const res = await getDutySchedules({ page: 1, pageSize: 1000 });
    schedules.value = res.schedules;
  } catch (error) {
    console.error("获取排班列表失败:", error);
    ElMessage.error("获取排班列表失败");
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.nurseId = null;
  searchForm.scheduleId = null;
  handleSearch();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  Object.assign(form, {
    id: null,
    nurseId: null,
    scheduleId: null,
    startTime: null,
    endTime: null,
    status: 1,
  });
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogType.value = "edit";
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          await createDutyRecord(form);
          ElMessage.success("新增成功");
        } else {
          await updateDutyRecord(form);
          ElMessage.success("更新成功");
        }
        dialogVisible.value = false;
        fetchData();
      } catch (error) {
        console.error("保存失败:", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

// 删除
const handleDelete = async (row) => {
  try {
    await deleteDutyRecord(row.id);
    ElMessage.success("删除成功");
    fetchData();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败");
  }
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 初始化
onMounted(() => {
  fetchData();
  fetchNurses();
  fetchSchedules();
});
</script>

<style scoped>
.duty-record-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
